// Copyright (c) 2009 Hypirinha contributers
// This program is made available under the terms of the MIT License.
package org.hypirinha.html.elements.implementations;

import org.hypirinha.html.Content;
import org.hypirinha.html.Text;
import org.hypirinha.html.attributes.AnyAttribute;
import org.hypirinha.html.elements.Contains;
import org.hypirinha.html.output.Visitor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public abstract class Element<S, C extends Content> implements Contains<S, C> {

    private String name;
    private List<AnyAttribute> attributes = new ArrayList<AnyAttribute>();
    private List<Content> children = new ArrayList<Content>();

    public Element(String name, AnyAttribute... attributes) {
        this.name = name;
        this.attributes.addAll(Arrays.asList(attributes));
    }

    protected <T extends Content> T newChild(T newChild) {
        children.add(newChild);
        return newChild;
    }

    @SuppressWarnings("unchecked")   
    public S contains(C... contents) {
        for (Content content : contents) {
            newChild(content);
        }
        return (S) this;
    }

    public void visit(Visitor visitor) {
        visitor.startTag(name, attributes.toArray(new AnyAttribute[attributes.size()]));
        for (Content child : children) {
            child.visit(visitor);
        }
        visitor.endTag();
    }
}
